package edu.chl.food_store.beans.control;

import edu.chl.food_store.beans.model.ShoppingCartModelBean;
import edu.chl.food_store.utility.*;
import javax.faces.bean.*;

/**
 * BuyController:
 * Managed bean for purchasing items and email confirmation. 
 */
@ManagedBean
@RequestScoped
public class BuyController {

    //injects required data.
    @ManagedProperty(value = "#{shoppingCartModelBean}")
    private ShoppingCartModelBean cartBean;
    @ManagedProperty(value = "#{loginModelBean.email}")
    private String email;

    public void buyAndEmptyCart() {
        //Create message
        StringBuilder message = new StringBuilder();
        message = message.append("YOU HAVE BOUGHT: \n");
        for (CartItem item : cartBean.getCart()) {
            message.append(item.getProduct().getName());
            message.append(" Price: ");
            message.append(item.getProduct().getPrice());
            message.append(" Quantity: ");
            message.append(item.getQuantity());
            message.append(" Sum: ");
            message.append(item.getProduct().getPrice() * item.getQuantity());
            message.append("\n");
        }
        message.append("\n\nTotal price of products: ");
        message.append(cartBean.getTotalPrice());
        message.append("\n\nThank you for shopping at Chalmers Food Store!");
        //Send mail
        try {
            Mailer.sendMail(message.toString(), email);
        } catch (Exception e) {
            System.out.println("Error while sending e-mail receipt!");
        }
        //Empty Cart
        cartBean.emptyCart();
    }

    public ShoppingCartModelBean getCartBean() {
        return cartBean;
    }

    public void setCartBean(ShoppingCartModelBean cartBean) {
        this.cartBean = cartBean;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
